<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="cartInfo in cartInfoList"
          :key="cartInfo.id"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="!!cartInfo.isChecked"
              @click="changeChecked(cartInfo)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">
              {{ cartInfo.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="changeShopCarNum('del', cartInfo, $event)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="cartInfo.skuNum"
              minnum="1"
              class="itxt"
              @change="changeShopCarNum('update', cartInfo, $event)"
            />
            <a
              href="javascript:;"
              class="plus"
              @click="changeShopCarNum('add', cartInfo, $event)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:;"
              class="sindelet"
              @click="deleteOneShopCartStates(cartInfo.skuId)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="allCheck" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="deleteShopCar">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ isCheckedShopCart }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ AllPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link to="/login" class="sum-btn">结算</router-link>
        </div>
      </div>
      <!-- 弹出框组件 -->
      <Dialog :visible.sync="visible">
        <template v-slot:header>
          <p>提示</p>
        </template>
        <template>
          <p>您真的确定要删除此条数据吗？</p>
        </template>
        <template #footer>
          <div class="btn-footer">
            <button class="btn btn-cancle" @click="closeDailog">取消</button>
            <button class="btn btn-primary" @click="deleteOneShopCartStatesBtn">
              确定
            </button>
          </div>
        </template>
      </Dialog>
    </div>
  </div>
</template>

<script>
import { skuNumReg } from "@/utils/reg";
import {
  reqShopCartListData,
  reqChangeCartState,
  reqChangeAllCartState,
  reqDeleteShopCartOne,
  reqAddOrUpdateCart,
} from "@/api";
export default {
  name: "ShopCart",
  data() {
    return {
      // 购物车所有商品信息
      cartInfoList: [],
      visible: false,
      isDeleted: false,
      shopCartOneId: 0,
      skuIdList: [],
    };
  },
  methods: {
    async getShopCartState() {
      //挂载时请求购物车需要渲染的数据
      let result = await reqShopCartListData();
      if (result.code == 200) {
        console.log(result);
        this.cartInfoList = result.data.length
          ? result.data[0].cartInfoList
          : [];
      } else {
        console.log(result.message);
      }
    },
    // 改变单个按钮状态
    async changeChecked(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked;
      const result = await reqChangeCartState(cartInfo.skuId, isChecked);
      if (result.code == 200) {
        // this.cartInfoList = result.data;
        // console.log(result);
        // 更新服务器数据成功后，重新更新页面
        cartInfo.isChecked = isChecked;
      } else {
        console.log(result.message);
      }
      // 将data中缓存的第一次数据中的isChecked状态更改
      // this
    },
    // 隐藏弹框
    closeDailog() {
      this.visible = false;
    },
    // 创建删除函数,删除购物车种商品信息
    deleteOneShopCartStates(id) {
      // 提示框显示
      this.visible = true;
      // 判断是否为删除选择 为false时表示是删除单个商品信息
      this.isDeleted = false;
      // 将获取到的id存入data中
      this.shopCartOneId = id;

      console.log(id);
    },
    // 点击删除购物车中列表信息
    async deleteOneShopCartStatesBtn() {
      this.visible = false;
      // 发送请求删除商品信息
      await reqDeleteShopCartOne(this.shopCartOneId);

      // 删除商品信息后重新发送请求动态渲染页面
      this.getShopCartState();
    },
    //删除选中购物车信息
    deleteShopCar() {
      this.cartInfoList = this.cartInfoList.filter((item) => {
        return item.isChecked !== 1;
      });
    },

    //手动修改购物车商品数量并动态渲染
    async changeShopCarNum(Type, cartInfo, e) {
      let num = 0;
      // 新值
      let newValue, oldValue;

      // 判断是什么操作,是加还是减,还是直接修改
      switch (Type) {
        case "add":
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++;
            num++;
          }
          break;
        case "del":
          if (cartInfo.skuNum > 1) {
            cartInfo.skuNum++;
            num++;
          }
          break;
        case "update":
          // 在输入框中实时渲染的数值
          newValue = e.target.value;
          // 请求中自带的数值
          oldValue = cartInfo.skuNum;
          if (skuNumReg.test(newValue)) {
            // 如果你输入的值符合正则表达式那么就将新值进行赋值
            cartInfo.skuNum = newValue;

            if (newValue > 200) {
              cartInfo.skuNum = 200;
              num = 200 - oldValue;
            } else {
              e.target.value = oldValue;
              num = 0;
            }
          }
          break;
      }

      // 在此处判断num是否为0
      if (num == 0) return;
      // 此处重回新发送请求  num为数量差值
      const result = await reqAddOrUpdateCart(this.shopCartOneId, num);
      if (result.code == 200) {
        this.cartInfoList = result;
        // 请求回新的数据
      } else {
        console.log(result.message);
      }
    },
  },
  computed: {
    // 全选按钮状态
    allCheck: {
      get() {
        return (
          this.cartInfoList.every((item) => item.isChecked == 1) &&
          this.cartInfoList.length
        );
      },
      async set(val) {
        // 用变量保存全选按钮的现在值
        let isChecked = val ? 1 : 0;
        let idList = [];
        this.cartInfoList.forEach((item) => {
          item.isChecked = isChecked;

          idList.push(item.skuId);
        });

        // 统一批量更新选中状态
        const result = await reqChangeAllCartState(isChecked, idList);
        if (result.code === 200) {
          alert("更新成功...");
        } else {
          console.log("更新失败...");
        }
        // this.reqChangeAllCartState(isChecked, idList);
        // if (result.code == 200) {
        //   // this.cartInfoList = result.data;
        //   // console.log(result);
        //   // 更新服务器数据成功后，重新更新页面
        //   cartInfo.isChecked = isChecked;
        // } else {
        //   console.log(result.message);
        // }
      },
    },
    // 计算出以被选中的商品
    isCheckedShopCart() {
      return this.cartInfoList.filter((item) => {
        return item.isChecked == 1;
      }).length;
    },
    // 计算出总价格
    AllPrice() {
      let arrPrice = [];
      this.cartInfoList.forEach((item) => {
        if (item.isChecked == 1) arrPrice.push(item.cartPrice);
      });
      let price = arrPrice.reduce((prevent, current) => {
        return prevent + current;
      }, 0);
      // this.cartInfoList.reduce((prevent, current) => {
      // prevent+current.isChecked*current.skuPrice * current.skuNum
      // }, 0);
      return price;
    },
  },
  async mounted() {
    // 当组件挂载时发送请求 获取购物车数据
    await this.getShopCartState();
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
  .btn-footer {
    position: absolute;
    right: 30px;
    bottom: 20px;
    .btn {
      width: 66px;
      height: 34px;
      margin-right: 6px;
      cursor: pointer;
      border: none;
      border-radius: 3px;
      font-size: 14px;
      &.btn-primary {
        background-color: #409eff;
        color: #fff;
      }
      &:hover {
        background-color: #66bff6;
      }
      &.btn-cancle {
        border: 1px solid #ccc;
        &:hover {
          background-color: #ecf5ff;
          color: #47a2ff;
        }
      }
    }
  }
}
</style>